package br.com.linkers.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.linkers.data.HibernateUtil;
import br.com.linkers.entity.Telefones;
import br.com.linkers.entity.Usuarios;

public class TelefoneDAO {

	Session session = HibernateUtil.getSessionFactory().openSession();
	Transaction transaction = session.beginTransaction();

	List<Telefones> lista;

	public void newSession() {
		this.session = HibernateUtil.getSessionFactory().openSession();
		this.transaction = session.beginTransaction();
	}

	public void inserir(Telefones telefone) {

		newSession();

		session.persist(telefone);

		transaction.commit();
		session.close();
	}

	public void deletar(Telefones telefone) {

		newSession();

		session.delete(telefone);

		transaction.commit();
		session.close();
	}

	public void atualizar(Telefones telefone) {
		newSession();
		session.update(telefone);
		transaction.commit();
		session.close();
	}

	public Telefones buscaPorIdUsuarioUltimo(Long id){
		newSession();
		Usuarios u = new Usuarios();
		u.setId(id);
		Criteria cri = session.createCriteria(Telefones.class)
				.add(Restrictions.eq("usuario", u));
		List<Telefones> results = cri.list();
		session.close();
		if(results.size()>0){
			return (Telefones) results.get(results.size()-1);
		}else{
			return null;
		}

	}
	
	public List<Telefones> buscaPorIdUsuario(Long id){
		newSession();
		Usuarios u = new Usuarios();
		u.setId(id);
		Criteria cri = session.createCriteria(Telefones.class)
				.add(Restrictions.eq("usuario", u));
		this.lista = cri.list();
		return this.lista;
	}

	public List<Telefones> listar() {
		newSession();
		Criteria cri = session.createCriteria(Telefones.class);
		this.lista = cri.list();
		return this.lista;
	}
}